package com.example.imoocmall.service.impl;

import com.example.imoocmall.common.Constant;
import com.example.imoocmall.exception.ImoocMallException;
import com.example.imoocmall.exception.ImoocMallExceptionEnum;
import com.example.imoocmall.filter.UserFilter;
import com.example.imoocmall.model.dao.CartMapper;
import com.example.imoocmall.model.dao.OrderMapper;
import com.example.imoocmall.model.dao.Order_itemMapper;
import com.example.imoocmall.model.dao.ProductMapper;
import com.example.imoocmall.model.pojo.Cart;
import com.example.imoocmall.model.pojo.Order;
import com.example.imoocmall.model.pojo.Order_item;
import com.example.imoocmall.model.pojo.Product;
import com.example.imoocmall.model.request.CreateOrderReq;
import com.example.imoocmall.model.vo.CartVo;
import com.example.imoocmall.model.vo.OrderVo;
import com.example.imoocmall.model.vo.Order_itemVo;
import com.example.imoocmall.service.OrderService;
import com.example.imoocmall.service.UserService;
import com.example.imoocmall.util.OrderCodeFactory;
import com.example.imoocmall.util.QRCodeGenerator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.zxing.WriterException;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 订单实现类
 */
@Service
@AllArgsConstructor
public class OrderServiceImpl implements OrderService {

    CartServiceImpl cartService;

    ProductMapper productMapper;

    CartMapper cartMapper;

    OrderMapper orderMapper;

    Order_itemMapper order_itemMapper;

    UserService userService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public String create(CreateOrderReq createOrderReq){
        //获取用户id
        Integer userId = UserFilter.currentUser.getId();
        //找到该用户的购物车
        List<CartVo> list = cartService.list(userId);
        //找到购物车中选中的商品
        List<CartVo> selectedCartVoList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            CartVo cartVo =  list.get(i);
            if (cartVo.getSelected().equals(Constant.SaleSelect.CHECKED)){
                selectedCartVoList.add(cartVo);
            }
        }
        list = selectedCartVoList;
        //判断商品是否存在,是否上架,库存够不够
        for (int i = 0; i < selectedCartVoList.size(); i++) {
            CartVo cartVo =  selectedCartVoList.get(i);
            Product product = productMapper.selectByPrimaryKey(cartVo.getProductId());
            if (product==null || product.getStatus().equals(Constant.SaleStatus.NOT_SALE)){
                throw new ImoocMallException(ImoocMallExceptionEnum.NOT_SALE);
            }
            if (cartVo.getQuantity()>product.getStock()){
                throw new ImoocMallException(ImoocMallExceptionEnum.NOT_SALE_NUM);
            }
        }
        //生产订单了开始
        Order order = new Order();
        order.setOrderNo(OrderCodeFactory.getOrderCode(userId));

        //设置订单总价格为0
        int order_price = 0;

        //把购物车中选中的商品创建item对象
        List<Order_item> order_itemList = new ArrayList<>();
        for (int i = 0; i < selectedCartVoList.size(); i++) {
            CartVo cartVo =  selectedCartVoList.get(i);
            Order_item order_item = new Order_item();
            order_item.setProductId(cartVo.getProductId());
            order_item.setProductName(cartVo.getProductName());
            order_item.setProductImg(cartVo.getProductImage());
            order_item.setUnitPrice(cartVo.getPrice());
            order_item.setQuantity(cartVo.getQuantity());
            order_item.setTotalPrice(cartVo.getTotalPrice());
            order_item.setOrderNo(order.getOrderNo());
            order_itemList.add(order_item);


            order_price +=cartVo.getTotalPrice();
        }
        //清除库存
        for (int i = 0; i < selectedCartVoList.size(); i++) {
            CartVo cartVo =  selectedCartVoList.get(i);
            Product product = productMapper.selectByPrimaryKey(cartVo.getProductId());
            int count = product.getStock() - cartVo.getQuantity();
            if (count <0){
                throw new ImoocMallException(ImoocMallExceptionEnum.NOT_SALE_NUM);
            }else {
                product.setStock(count);
                productMapper.updateByPrimaryKeySelective(product);
            }
        }
        //删除购物车中选中的商品
        for (CartVo cartVo : list) {
            cartMapper.deleteByPrimaryKey(cartVo.getId());
        }

        //order的剩下部分
        order.setUserId(userId);
        order.setTotalPrice(order_price);
        order.setReceiverName(createOrderReq.getReceiverName());
        order.setReceiverAddress(createOrderReq.getReceiverAddress());
        order.setReceiverMobile(createOrderReq.getReceiverMobile());
        order.setOrderStatus(Constant.OrderStatusEnum.NOT_PAID.getCode());
        order.setPostage(createOrderReq.getPostage());
        order.setPaymentType(createOrderReq.getPaymentType());

        //order写入数据库
        orderMapper.insertSelective(order);

        //item写入数据库
        for (int i = 0; i < order_itemList.size(); i++) {
            Order_item order_item =  order_itemList.get(i);
            order_itemMapper.insertSelective(order_item);
        }
        return order.getOrderNo();


        //拿到用户id
//        Integer userId = UserFilter.currentUser.getId();
//        //从购物车中拿到已经选中的商品
//        List<CartVo> cartVoList = cartService.list(userId);
//        List<CartVo> selectedCartVolist = new ArrayList<>();
//        for (CartVo cartVo : cartVoList) {
//            if (cartVo.getSelected().equals(Constant.SaleSelect.CHECKED)) {
//                selectedCartVolist.add(cartVo);
//            }
//        }
//        //没有商品报错空
//        if (selectedCartVolist.size()==0){
//            throw new ImoocMallException(ImoocMallExceptionEnum.CART_EMPTY);
//        }
//        //判断商品是否存在.是否上下架,库存够不够
//        validSaleStatusAndStock(selectedCartVolist);
//        //吧购物车对象转换为订单item对象
//        List<Order_item> order_itemList = cartVOListToOrderItemList(selectedCartVolist);
//        //扣库存
//        for (int i = 0; i < order_itemList.size(); i++) {
//            Order_item order_item =  order_itemList.get(i);
//            Product product = productMapper.selectByPrimaryKey(order_item.getProductId());
//            if ((product.getStock()-order_item.getQuantity())>0){
//                product.setStock(product.getStock()-order_item.getQuantity());
//                productMapper.updateByPrimaryKeySelective(product);
//            }else{
//                throw new ImoocMallException(ImoocMallExceptionEnum.NOT_SALE_NUM);
//            }
//
//        }
//        //删除购物车中的已经勾选的商品
//        cleanCart(selectedCartVolist);
//        //生产订单:
//        Order order = new Order();
//        //生产订单号的规则
//        String orderNo = OrderCodeFactory.getOrderCode(userId);
//        order.setOrderNo(orderNo);
//        order.setUserId(userId);
//        order.setTotalPrice(totalPrice(order_itemList));
//        order.setReceiverName(createOrderReq.getReceiverName());
//        order.setReceiverAddress(createOrderReq.getReceiverAddress());
//        order.setReceiverMobile(createOrderReq.getReceiverMobile());
//        order.setPostage(createOrderReq.getPostage());
//        order.setPaymentType(createOrderReq.getPaymentType());
//        order.setOrderStatus(Constant.OrderStatusEnum.NOT_PAID.getCode());
//        //插入到order表
//        orderMapper.insertSelective(order);
//        //循环保存每个商品到order_item表
//        for (int i = 0; i < order_itemList.size(); i++) {
//            Order_item order_item =  order_itemList.get(i);
//            order_item.setOrderNo(order.getOrderNo());
//            order_itemMapper.insertSelective(order_item);
//        }
//        //把结果返回
//        return orderNo;
    }
//
//    private void validSaleStatusAndStock(List<CartVo> cartVos){
//        for (int i = 0; i < cartVos.size(); i++) {
//            CartVo cartVo =  cartVos.get(i);
//
//            Product product = productMapper.selectByPrimaryKey(cartVo.getProductId());
//            //判断是否上架,是否存在
//            if (product == null || product.getStatus().equals(Constant.SaleStatus.NOT_SALE)){
//                throw new ImoocMallException(ImoocMallExceptionEnum.NOT_SALE);
//            }
//            //判断库存
//            if (cartVo.getQuantity()>product.getStock()){
//                throw new ImoocMallException(ImoocMallExceptionEnum.NOT_SALE_NUM);
//            }
//
//        }
//    }
//    private List<Order_item> cartVOListToOrderItemList(List<CartVo> cartVoList){
//        List<Order_item> order_itemList = new ArrayList<>();
//
//        for (int i = 0; i < cartVoList.size(); i++) {
//            CartVo cartVo =  cartVoList.get(i);
//            Order_item order_item = new Order_item();
//            order_item.setProductId(cartVo.getProductId());
//            //商品当前记录快照
//            order_item.setProductName(cartVo.getProductName());
//            order_item.setProductImg(cartVo.getProductImage());
//            order_item.setQuantity(cartVo.getQuantity());
//            order_item.setUnitPrice(cartVo.getPrice());
//            order_item.setTotalPrice(cartVo.getTotalPrice());
//            order_itemList.add(order_item);
//        }
//        return order_itemList;
//    }
//    private void cleanCart(List<CartVo> cartVoList){
//        for (int i = 0; i < cartVoList.size(); i++) {
//            CartVo cartVo =  cartVoList.get(i);
//
////            Cart cart = cartMapper.selectCartByUserIdAndProductId(UserFilter.currentUser.getId(),cartVo.getProductId());
////            if (cart == null){
////                throw new ImoocMallException(ImoocMallExceptionEnum.DELETE_FAILED);
////            }else{
////                cartMapper.deleteByPrimaryKey(cart.getId());
////            }
//            cartMapper.deleteByPrimaryKey(cartVo.getId());
//        }
//    }
//    private Integer totalPrice(List<Order_item> order_itemList){
//        Integer totalPrice = 0;
//        for (int i = 0; i < order_itemList.size(); i++) {
//            Order_item order_item =  order_itemList.get(i);
//            totalPrice = totalPrice+order_item.getTotalPrice();
//        }
//        return totalPrice;
//    }

    @Override
    public OrderVo detail(String orderNo){
        Order order = orderMapper.selectByOrderNo(orderNo);
        if (order == null){
            throw new ImoocMallException(ImoocMallExceptionEnum.NO_ORDER);
        }
        //订单存在需要判断所属
        Integer userId = UserFilter.currentUser.getId();
        if (!order.getUserId().equals(userId)){
            throw new ImoocMallException(ImoocMallExceptionEnum.NOT_YOUR_ORDER);
        }
        OrderVo orderVo = getOrderVo(order);
        return orderVo;
    }

    private OrderVo getOrderVo(Order order){
        //把order能展示出来的都放到ordervo上线
        OrderVo orderVo = new OrderVo();
        BeanUtils.copyProperties(order,orderVo);
        //然后开始弄ordervo中的order_itemvo
        List<Order_itemVo> orderItemVoList = order_itemMapper.getOrder_itemVo(order.getOrderNo());
        orderVo.setOrderItemVoList(orderItemVoList);
        orderVo.setOrderStatus(Constant.OrderStatusEnum.codeOf(order.getOrderStatus()).getValue());

        return orderVo;
    }

    @Override
    public PageInfo listForController(Integer pageNum, Integer pageSize){
        PageHelper.startPage(pageNum,pageSize,"create_time"+" "+"desc");
        Integer userId = UserFilter.currentUser.getId();
        List<Order> orders = orderMapper.selectByUserId(userId);
        List<OrderVo> orderVoList = new ArrayList<>();
        for (int i = 0; i < orders.size(); i++) {
            Order order =  orders.get(i);
            OrderVo orderVo = detail(order.getOrderNo());
            orderVoList.add(orderVo);
        }
        PageInfo pageInfo = new PageInfo(orderVoList);
        return pageInfo;
    }



    @Override
    public void cancel(String orderNo){
        Integer userId = UserFilter.currentUser.getId();
        Order order = orderMapper.selectByOrderNo(orderNo);
        //判断订单存不存在
        if (order == null){
            throw new ImoocMallException(ImoocMallExceptionEnum.NO_ORDER);
        }
        //判断订单是不是当前登录的人
        if (!order.getUserId().equals(userId)){
            throw new ImoocMallException(ImoocMallExceptionEnum.NOT_YOUR_ORDER);
        }
        //验证当前的订单状态是未付款
        if (order.getOrderStatus().equals(Constant.OrderStatusEnum.NOT_PAID.getCode())){
            order.setOrderStatus(Constant.OrderStatusEnum.CANCELED.getCode());
            order.setEndTime(new Date());
            //更新订单状态
            orderMapper.updateByPrimaryKeySelective(order);
            //取消订单后-需要把库存加进去呀
            List<Order_itemVo> order_itemVos = order_itemMapper.getOrder_itemVo(order.getOrderNo());
            for (int i = 0; i < order_itemVos.size(); i++) {
                Order_itemVo order_itemVo =  order_itemVos.get(i);
                Product product = productMapper.selectByPrimaryKey(order_itemVo.getProductId());
                product.setStock(order_itemVo.getQuantity()+product.getStock());
                productMapper.updateByPrimaryKeySelective(product);
            }
        }else {
            throw new ImoocMallException(ImoocMallExceptionEnum.NOT_CANCEL);
        }
    }

    @Override
    public String qrcode(String orderNo){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        String address = Constant.ip + ":" + request.getLocalPort();
        String payUrl = "http://"+ address+"/pay?orderNo="+orderNo;
        try {
            QRCodeGenerator.generateQRCodeImage(payUrl,350,350,Constant.FILE_UPLOAD_DIR+orderNo+".png");
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String pngAddress = "http://"+address+"/images/"+orderNo+".png";
        return pngAddress;
    }


    @Override
    public void pay(String orderNo){
        Order order = orderMapper.selectByOrderNo(orderNo);
        //判断订单存不存在
        if (order == null){
            throw new ImoocMallException(ImoocMallExceptionEnum.NO_ORDER);
        }
        //判断订单是不是属于他
        Integer userId = UserFilter.currentUser.getId();
        if (!order.getUserId().equals(userId)){
            throw new ImoocMallException(ImoocMallExceptionEnum.NOT_YOUR_ORDER);
        }
        if (order.getOrderStatus() == Constant.OrderStatusEnum.NOT_PAID.getCode()){
            order.setOrderStatus(Constant.OrderStatusEnum.PAID.getCode());
            order.setPayTime(new Date());
            orderMapper.updateByPrimaryKeySelective(order);
        }else {
            throw new ImoocMallException(ImoocMallExceptionEnum.WRONG_ORDER_STUTUS);
        }
    }


    @Override
    public void finish(String orderNo){
        Order order = orderMapper.selectByOrderNo(orderNo);
        //判断订单存不存在
        if (order == null){
            throw new ImoocMallException(ImoocMallExceptionEnum.NO_ORDER);
        }
        //如果是普通用户-判断订单是不是属于他
        Integer userId = UserFilter.currentUser.getId();
        if (!userService.checkAdminRole(UserFilter.currentUser) && !order.getUserId().equals(userId)){//
            throw new ImoocMallException(ImoocMallExceptionEnum.NOT_YOUR_ORDER);
        }
        if (order.getOrderStatus() == Constant.OrderStatusEnum.DELIVERED.getCode()){
            order.setOrderStatus(Constant.OrderStatusEnum.FINISHED.getCode());
            order.setEndTime(new Date());
            orderMapper.updateByPrimaryKeySelective(order);
        }else {
            throw new ImoocMallException(ImoocMallExceptionEnum.WRONG_ORDER_STUTUS);
        }
    }

}














